﻿using lib472.API;
using libedi.API;
using System;
using System.IO;
using System.Net.Http;

namespace libedi
{

    public delegate void EventMessage(string File, bool isTrue, string error);
    public class DownLoadFile
    {

        private EventMessage @event;
        string savename=string.Empty;   

       public void LoadAsync(string FileName, EventMessage eventHandler)
        {
            this.@event = eventHandler;
            // 文件下载的 API URL
            string url = $"{Clientbuss.ApiUrl}/api/edi/LoadLog?FileName={FileName}";
            // 指定文件保存路径

            string PlugTemp = "PlugLog";
            string DirFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, PlugTemp);
            if (!Directory.Exists(DirFolder))
            {
                Directory.CreateDirectory(DirFolder);
            }
            string filePath = Path.Combine(DirFolder, FileName);

            // 下载文件
            DownloadFileAsync(url, filePath);
        }


        async void DownloadFileAsync(string url, string filePath)
        {
            using (HttpClient client = new HttpClient())
            {
                bool b = true;
                string mess = string.Empty; 
                try
                {
                    // 发送 GET 请求以下载文件
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容为字节流
                    byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

                    // 将字节流写入本地文件
                    System.IO.File.WriteAllBytes(filePath, fileBytes);

                }
                catch (Exception ex)
                {
                    b=false;
                    mess=$"{ex.Message}";
                }
                finally
                {
                    @event?.Invoke(filePath,b, mess);
                }
            }
        }

    }




}
